import { dicList, fileArraybuffer } from "@/api/common";
import { Notification } from "element-ui";
export default {
  // 将字符串按逗号分割成字符串数组，转化为数字数组用于表单select多选回显
  stringToArray(obj) {
    if (obj.indexOf(",") !== -1) {
      const str = obj.split(",");
      return str.map(Number);
    } else {
      console.log(obj);
      const str = obj.split();
      return str.map(Number);
    }
  },
  checkString(obj) {
    if (obj.indexOf(",") !== -1) {
      return obj.split(",");
    } else {
      return obj.split();
    }
  },
  // 是否是空对象
  isEmptyObj(value) {
    if (
      typeof value === "undefined" ||
      value === null ||
      typeof value !== "object"
    ) {
      return true;
    }
    for (const name in value) {
      if (Object.prototype.hasOwnProperty.call(value, name)) {
        return false;
      }
    }
    return true;
  },
  // 将json数据转换成FormData格式
  convertFormData(data) {
    if (!this.isEmptyObj(data)) {
      const formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      return formData;
    }
    return data;
  },
  isHasPower(type) {
    const result = {
      "tbr": ["hb_tbr", "hb_sys"],
      "spr": ["hb_spr", "hb_sys"]
    };
    const roleCodeList = JSON.parse(sessionStorage.getItem("role")).roleCode.split(",");
    return result[type].some(i => roleCodeList.includes(i));
  },
  // 判断是否是下一步操作人
  isNextUser(ids) {
    const nowUser = JSON.parse(sessionStorage.getItem("account")).id;
    const powerList = ids ? ids.split(",") : [];
    return powerList.includes(nowUser);
  },
  // 判断当前按钮权限
  isBtnPower(_this, btnName) {
    const nowPowerList = _this.$store.state.nowPowerList || [];
    if (nowPowerList.length > 0) {
      const nowPower = nowPowerList.find(i => i.btnName === btnName) || {};
      if (nowPower.id) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  },
  /**
 * 获取字典表数据的公共函数
 * @param {String|Array} code - 字典表code 单个可传一个字符串，多个传入字符串数组
 * @param {String|Array} list - 返回结果中对应的键名或键名数组 单个可传一个字符串，多个传入字符串数组
 * @param {Object} returnName - 返回结果的格式，默认label、value
 * @returns {Object} - 包含结果数据或错误信息的对象
 */
  async getDicCommon(code, list, returnName) {
    const isArray = Array.isArray(code); // 判断code是否为数组
    const codes = isArray ? code : [code]; // 统一将code处理为数组
    const hasReturnName = !!returnName; // 判断是否传入了returnName
    try {
      const resultList = await Promise.all(codes.map(code => dicList({ code }))); // 使用Promise.all并发获取字典表数据
      // 根据返回结果和传入参数，生成最终的结果对象
      const results = resultList.reduce((acc, result, index) => {
        const key = isArray ? list[index] : list;
        if (!hasReturnName) {
          acc[key] = result.map(i => {
            return {
              label: i.dicName,
              value: i.id
            };
          });
        } else {
          acc[key] = result.map(i => {
            const item = {};
            for (const [key, value] of Object.entries(returnName)) {
              item[key] = i[value];
            }
            return item;
          });
        }
        return acc;
      }, {});
      return { data: results };
    } catch (error) {
      console.error(error);
      return { error: error.message };
    }
  },
  /**
 * 流数据导出下载
 * @param {blob} res blob流
 * @param {String} fileName 下载文件名: xxx.xlsx
 */
  downloadByBlob(res, fileName) {
    const blob = new Blob([res], { type: "application/octet-stream" });
    const blobUrl = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.style.display = "none";
    a.download = fileName; // 文件名
    a.href = blobUrl;
    a.click();
  },
  // pdf预览
  pdfPreview(id, name) {
    const rg = /\.([\w]+)$/;
    const type = name.match(rg)[1];
    if (!["PDF", "pdf"].includes(type)) {
      return Notification({
        message: "非PDF文件请先下载再查看！",
        type: "warning"
      });
    }
    fileArraybuffer({ id }).then(res => {
      const a = document.createElement("a");
      const blob = new Blob([res], { type: "application/pdf" });
      const objectUrl = URL.createObjectURL(blob);
      a.setAttribute("href", objectUrl);
      a.setAttribute("target", "_blank");
      a.click();
      a.remove();
    });
  }
};
